package com.weixing.mall.provider.model.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.provider.model.domain.BuySample;
import com.weixing.mall.provider.service.IBuySampleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 买板导入
 */
public class BuySampleImportDataListener extends AnalysisEventListener<BuySampleExcelData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(BuySampleImportDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    List<BuySampleExcelData> list = new ArrayList<>();

    //操作人Id
    private Long operatorId;

    private IBuySampleService buySampleService;
    public BuySampleImportDataListener(IBuySampleService buySampleService,Long operatorId){
        this.buySampleService = buySampleService;
        this.operatorId = operatorId;
    }

    @Override
    public void invoke(BuySampleExcelData data, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        //这里用不上
        /*if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }*/
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        handleData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 处理数据
     */
    void handleData() {
        LOGGER.info("{}条数据！", list.size());
        if(list.size() ==0 ){
            throw new BusinessException("导入数据为空");
        }
        //装载插入数据的集合
        List<BuySample> savelist = Lists.newArrayList();
        if(list.size() > 0){
            for (BuySampleExcelData bs:list){
                BuySample buySample = new BuySample();
                BeanUtils.copyProperties(bs,buySample);
                //设置状态
                buySample.setIsTakePhoto(0);//0否 1是  是否拍照
                buySample.setIsOnShelf(0);//0否 1是    是否上架
                //设置操作人
                buySample.setCreatedBy(operatorId);

                savelist.add(buySample);
            }
        }
        if(savelist.size() >0){
           //插入数据
           buySampleService.batchInsertImportData(savelist);
        }
        LOGGER.info("导入完成！");
    }
}
